package com.yudaxian.bi.controller;

import cn.hutool.json.JSONUtil;
import com.yudaxian.bi.common.BaseResponse;
import com.yudaxian.bi.common.ResultUtils;
import com.yudaxian.bi.config.ThreadPoolExecutorConfig;
import io.netty.util.concurrent.CompleteFuture;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author: yudaxian
 * @Description: TODO
 * @DateTime: 2024/9/21 10:18
 **/
@RestController
@RequestMapping("/queue")
@Api(tags = "队列管理（测试）")
@Slf4j
public class QueueController {

    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @PostMapping("/add")
    @ApiOperation(value = "添加任务")
    public void addQueue(@RequestBody String name) {
        CompletableFuture.runAsync(() -> {
            // 执行一个没有返回值的任务
            log.info("任务执行中：{}, 执行人 : {}", name, Thread.currentThread().getName());
            log.info("开始睡觉，60s");
            try {
                Thread.sleep(60000);
                log.info("睡觉结束，执行人： {},继续执行任务", Thread.currentThread().getName());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            // 把任务放到自己定义的线程池中
        }, threadPoolExecutor);
    }

    @PostMapping("/get")
    @ApiOperation(value = "获取任务")
    public BaseResponse getQueue() {
        Map<String, Object> result = new HashMap<>();

        int size = threadPoolExecutor.getQueue().size();
        result.put("队列长度：", size);
        long taskCount = threadPoolExecutor.getTaskCount();
        result.put("任务总数：", taskCount);
        long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
        result.put("已完成任务数：", completedTaskCount);
        int activeCount = threadPoolExecutor.getActiveCount();
        result.put("正在工作的线程数：", activeCount);
        return ResultUtils.success(result);
    }

}
